package com.leyou.auth.interceptor;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.common.constants.JwtConstants.COOKIE_NAME;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private JwtUtils jwtUtils;

    //这不是spring创建的类，不能用@Autowired，只能用构造方法传参
    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        //2.判断是否存在
        if (jwt == null){
            throw new LyException(401,"用户未登录！");
        }
        //3.校验jwt
        Payload payload = jwtUtils.parseJwt(jwt);
        //4.存储用户信息和JWT
        UserContext.setUser(payload.getUserDetail());
        UserContext.setJwt(jwt);
        //5.如果正确，则放行
        log.debug("用户{}正在访问路径：{}", payload.getUserDetail().getUsername(), request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeJwt();
        // 业务结束后，移除用户
        UserContext.removeUser();
    }
}
